import os.path

from flask import (
    Blueprint, request, session, current_app, send_from_directory, url_for,redirect
)

from .db import get_db
from .auth import login_required

bp = Blueprint('artwork', __name__, url_prefix='/artwork')


@bp.route('/p', methods=['GET','POST'])
def get_artwork_list():
    if request.method == 'GET':
        return send_from_directory(os.path.join(current_app.root_path, 'static'), 'artwork_list.html')
    if request.method == 'POST':
        db = get_db()
        db.execute(f"SELECT x.id, x.uid, x.title, y.nickname FROM artwork X LEFT JOIN _user Y ON X.uid=Y.uid ")
        records = db.fetchall()
        artwork_list = [
            {"id": records[0],
             "uid": record[1],
             "title": record[2],
             "nickname": record[3]
             }
            for record in records]
        return artwork_list


@bp.route('/p/<int:artwork_id>', methods=['GET','POST'])
# @login_required
def get_artwork(artwork_id):
    db = get_db()
    if request.method == 'GET':
        session['next_artwork_ID'] = artwork_id
        db.execute(f"SELECT * FROM artwork WHERE id='{artwork_id}'")
        record = db.fetchone()
        if record is None:
            return send_from_directory(os.path.join(current_app.root_path,'static'),'根本没有这个文件')
        return send_from_directory(os.path.join(current_app.root_path,'static'),'artwork.html')
    if request.method == 'POST':
        db.execute(f"SELECT uid FROM artwork WHERE id='{artwork_id}'")
        uid = db.fetchone()
        if uid is None:
            return{
                "status": "failed",
                "message": "没有这一条记录"
            }
        if session.get('uid') != uid:
            return{
                "status": "failed",
                "message": "没有权限删除非自己的帖子"
            }
        operation = request.json['operation']
        if operation == 'modify':
            title = request.json['title']
            content = request.json['html_content']
            db.execute(f"UPDATE artwork SET title='{title}', html_content='{content}'")
            return{
                "status": "success",
                "message": "修改成功"
            }
        if operation == 'delete':
            db.execute(f"DELETE FROM artwork WHERE id='{artwork_id}'")
            return{
                "status": "success",
                "message": "删除成功"
            }


@bp.route('/p/get-data',methods=['GET'])
def get_data():
    artwork_id = session.get('next_artwork_ID')
    db = get_db()
    db.execute(f"SELECT * FROM artwork WHERE id='{artwork_id}'")
    record = db.fetchone()
    if record is None:
        return redirect(url_for('static', filename='404.html'))
    return {
        "artwork_ID": record[0],
        "UID": record[1],
        "content": record[2],
        "artwork_url": record[3]
    }
